package com.yk.faceapplication.activity;

import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.allinpay.xed.R;
import com.android.volley.VolleyError;
import com.yk.faceapplication.MyApplication;
import com.yk.faceapplication.callback.RequestCallback;
import com.yk.faceapplication.http.RequestUrl;
import com.yk.faceapplication.util.ActivityUtil;
import com.yk.faceapplication.util.RequestUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by yk_2018/1/12_12:11
 */

public class RegisterActivity extends BaseActivity {
    private Button getCodeBtn, registerBtn;
    private EditText phoneET, codeET, pwdET;
    private Location location;

    private TextView registerTV, manageTV;
    private String url = null;
    private int time = 60;
    private final int SEND_MSG_SUCCESS = 100;
    private final int MSG_TIME = 101;
    private ImageView agreeIV;
    private LinearLayout agreeLayout;


    @Override
    protected void onHandleMessage(Message msg) {
        super.onHandleMessage(msg);
        switch (msg.what) {
            case SEND_MSG_SUCCESS:
                //                getCodeBtn.setEnabled(false);
                sendMessage(MSG_TIME);
                break;
            case MSG_TIME:
                if (time == 1) {
                    time = 60;
                    getCodeBtn.setText("获取验证码");
                    getCodeBtn.setEnabled(true);
                } else {
                    getCodeBtn.setText(--time + "");
                    sendMessageDelayed(MSG_TIME, 1000);
                }
                break;
        }
    }

    @Override
    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);
        setTitle("注册");
        agreeIV = (ImageView) findViewById(R.id.agree_img);
        registerTV = (TextView) findViewById(R.id.register_tv);
        manageTV = (TextView) findViewById(R.id.manage_tv);
        agreeLayout = (LinearLayout) findViewById(R.id.agree_layout);
        registerTV.setOnClickListener(this);
        manageTV.setOnClickListener(this);
        agreeLayout.setOnClickListener(this);
        getCodeBtn = (Button) findViewById(R.id.get_code_btn);
        phoneET = (EditText) findViewById(R.id.phone_et);
        codeET = (EditText) findViewById(R.id.code_et);
        pwdET = (EditText) findViewById(R.id.pwd_et);
        registerBtn = (Button) findViewById(R.id.register_btn);
        registerBtn.setOnClickListener(this);
        getCodeBtn.setOnClickListener(this);
        location = ((MyApplication) this.getApplicationContext()).getLocation();
        //        getUrl();
        phoneET.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // 输入的内容变化的监听
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // 输入前的监听

            }

            @Override
            public void afterTextChanged(Editable s) {
                // 输入后的监听
                checkInputInfo();
            }
        });
        codeET.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // 输入的内容变化的监听
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // 输入前的监听

            }

            @Override
            public void afterTextChanged(Editable s) {
                // 输入后的监听
                checkInputInfo();
            }
        });
        pwdET.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // 输入的内容变化的监听
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // 输入前的监听

            }

            @Override
            public void afterTextChanged(Editable s) {
                // 输入后的监听
                checkInputInfo();
            }
        });
        checkInputInfo();
    }

    private void checkInputInfo() {
        if (agreeIV.getVisibility() == View.INVISIBLE || ActivityUtil.editIsNull(phoneET) || ActivityUtil.editIsNull(pwdET) || ActivityUtil.editIsNull(codeET)) {
            registerBtn.setBackgroundColor(getResources().getColor(R.color.bg_gray));
            registerBtn.setEnabled(false);
            registerBtn.setTextColor(getResources().getColor(R.color.textBlack));
        } else {
            registerBtn.setBackgroundColor(getResources().getColor(R.color.textRegisterFile));
            registerBtn.setEnabled(true);
            registerBtn.setTextColor(getResources().getColor(R.color.white));
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.get_code_btn:
                if (!ActivityUtil.isMobileNO(phoneET.getText().toString().trim())) {
                    Toast.makeText(this, "请输入正确的手机号", Toast.LENGTH_SHORT).show();
                    return;
                }
                getCode();
                break;
            case R.id.register_btn:
                if (ActivityUtil.editIsNull(phoneET)) {
                    Toast.makeText(this, "请输入正确的手机号", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (ActivityUtil.editIsNull(codeET)) {
                    Toast.makeText(this, "请输入正确的验证码", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (pwdET.getText().toString().trim().length() < 6 || pwdET.getText().toString().trim().length() > 16 || !ActivityUtil.isPassworkFormat(pwdET.getText().toString().trim())) {
                    Toast.makeText(this, "密码为6-16位字符，包含字母和数字", Toast.LENGTH_SHORT).show();
                    return;
                }
                register();
                break;
            case R.id.register_tv:
            case R.id.manage_tv:
                Intent intent = new Intent(RegisterActivity.this, AgreeWebviewActivity.class);
                //                intent.putExtra("url","file:///android_asset/xed-agreement.htm");
                startActivity(intent);
                break;
            case R.id.agree_layout:
                if (agreeIV.getVisibility() == View.VISIBLE) {
                    agreeIV.setVisibility(View.INVISIBLE);
                } else {
                    agreeIV.setVisibility(View.VISIBLE);
                }
                checkInputInfo();
                break;
        }
    }


    //    获取验证码
    private void getCode() {
        getCodeBtn.setEnabled(false);
        Map<String, String> form = new HashMap<String, String>();
        form.put("flag", "0");
        form.put("mobile", phoneET.getText().toString());
        RequestCallback callback = new RequestCallback() {
            @Override
            public void success(JSONObject jsonObject) {
                Toast.makeText(RegisterActivity.this, "验证码发送成功", Toast.LENGTH_SHORT).show();
                sendMessage(SEND_MSG_SUCCESS);
            }

            @Override
            public void fail(VolleyError volleyError) {
                getCodeBtn.setEnabled(true);
            }
        };
        RequestUtil.request(this, RequestUrl.SEND_MSG, callback, form);
    }

    private void getUrl() {


        RequestCallback callback = new RequestCallback() {
            @Override
            public void success(JSONObject jsonObject) {
                try {
                    url = jsonObject.getString("data");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void fail(VolleyError volleyError) {

            }
        };
        RequestUtil.getRequest(this, RequestUrl.GET_REGISTER_URL, callback);
    }

    //    注册
    private void register() {
        String latitude = location == null ? "0" : location.getLatitude() + "";
        String longitude = location == null ? "0" : location.getLongitude() + "";
        Map<String, String> form = new HashMap<String, String>();
        form.put("mobile", phoneET.getText().toString());
        form.put("password", pwdET.getText().toString());
        form.put("code", codeET.getText().toString());
        form.put("latitude", latitude);
        form.put("longitude", longitude);
        form.put("useragentcode", "1");

        //        final Response.Listener<JSONObject> sListener = new Response.Listener<JSONObject>() {
        //            @Override
        //            public void onResponse(JSONObject jsonObject) {
        //                LogDebugger.info("success:" + jsonObject.toString());
        //                Toast.makeText(RegisterActivity.this, "注册成功", Toast.LENGTH_SHORT).show();
        //            }
        //        };
        //        final Response.ErrorListener eListener = new Response.ErrorListener() {
        //            @Override
        //            public void onErrorResponse(VolleyError volleyError) {
        //                volleyError.printStackTrace();
        //                LogDebugger.info("fail:" + volleyError.getMessage());
        //                Toast.makeText(RegisterActivity.this, "注册失败", Toast.LENGTH_SHORT).show();
        //            }
        //        };
        //
        //        final String jsonObject = com.alibaba.fastjson.JSONObject.toJSONString(form);
        //        try {
        //            JSONObject jObj = new JSONObject(jsonObject);
        //            JsonObjectRequest req = new JsonObjectRequest(Request.Method.POST, RequestUrl.REGISTER, jObj, sListener, eListener) {
        //
        //            };
        //            ((MyApplication) this.getApplicationContext()).getrQueue().add(req);
        //        } catch (Exception e) {
        //
        //        }


        RequestCallback callback = new RequestCallback() {
            @Override
            public void success(JSONObject jsonObject) {
                Toast.makeText(RegisterActivity.this, "注册成功", Toast.LENGTH_SHORT).show();
                finishAct();
            }

            @Override
            public void fail(VolleyError volleyError) {

            }
        };
        RequestUtil.request(this, RequestUrl.REGISTER, callback, form);
    }


}
